<template>
  <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
      
         <!-- 卡片区域 -->
          <el-card>
                  <!-- 警告区域 -->
                  <el-alert show-icon  :closable="false" title="注意：只允许为第三级分类设置相关参数" type="warning"> </el-alert>
              <!-- 选择商品分类区域 -->
              <el-row class="cap_opt">
                  <el-col>
                      <span>选择商品分类：</span>
                      <!-- 级联选择器 -->
                      <el-cascader
                         v-model="selectedKeys"
                        :options="cateList"
                        @change="cateHandleChange"
                        expand-trigger="hover"
                        :props="cascaderProps" clearable >
                      </el-cascader>
                  </el-col>
              </el-row>
              <!-- 标签页 -->
               <el-tabs v-model="activeName" @tab-click="handleTabClick">
                    <el-tab-pane label="动态参数" name="many">
                        <el-button :disabled="isBtnDisable" @click="showAdddialog" type = "primary">添加参数</el-button>
                        <!-- 动态参数表格 -->
                          <el-table :data="manyTableData" border stripe>
                              <!-- 扩展行 -->
                            <el-table-column type="expand">
                                <template slot-scope="scope"> 
                                     <!-- 循环渲染标签 -->
                                     <el-tag closable @close="handleTagClose(scope.row,index)" class="attr_val_tag" v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>                             
                                     <!-- 输入的文本框 -->
                                        <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                        >
                                        </el-input>
                                        <!-- 添加按钮 -->
                                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                </template>
                               
                            </el-table-column>
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作">
                                <!-- 操作 -->
                                <template slot-scope="scope">
                                  <el-button @click="showEditDialog(scope.row)" type="primary" size="mini" icon="el-icon-edit"></el-button>
                                  <el-button @click="removeParams(scope.row)" type="danger" size="mini" icon="el-icon-delete"></el-button>                 
                                </template>
                            </el-table-column>
                          </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="静态属性" name="only">
                         <el-button :disabled="isBtnDisable" @click="showAdddialog" type = "primary">添加属性</el-button>
                         <!-- 静态属性表格 -->
                         <el-table :data="onlyTableData" border stripe>
                            <el-table-column type="expand">
                                 <!-- 扩展行 -->
                                  <template slot-scope="scope">                                
                                     <el-tag closable @close="handleTagClose(scope.row,index)" class="attr_val_tag" v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>                             
                                      <!-- 输入的文本框 -->
                                        <el-input
                                        class="input-new-tag"
                                        v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)"
                                        >
                                        </el-input>
                                        <!-- 添加按钮 -->
                                      <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="#"></el-table-column>
                            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作">
                                <!-- 操作 -->
                                <template slot-scope="scope">
                                  <el-button @click="showEditDialog(scope.row)" type="primary" size="mini" icon="el-icon-edit"></el-button>
                                  <el-button @click="removeParams(scope.row)" type="danger" size="mini" icon="el-icon-delete"></el-button>                 
                                </template>
                            </el-table-column>
                          </el-table>
                    </el-tab-pane>
                  
               </el-tabs>
          </el-card>
          <!-- 添加参数对话框 -->
          <el-dialog
            :title="'添加'+addDialogTitle"
            :visible.sync="addDialogVisible"
            width="50%"
            @close = "addDialogClosed">
           <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
             <el-form-item :label="addDialogTitle" prop="attr_name">
              <el-input v-model="addForm.attr_name"></el-input>
             </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 编辑对话框 -->
           <el-dialog
            :title="'编辑'+addDialogTitle"
            :visible.sync="editDialogVisible"
            width="50%"
            @close = "editDialogClosed">
           <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="addFormRules">
             <el-form-item :label="addDialogTitle" prop="attr_name">
              <el-input v-model="editForm.attr_name"></el-input>
             </el-form-item>
           </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
          </el-dialog>
  
  </div>
</template>

<script>
export default {
         data() {
             return {
                 cateList:[],

                 selectedKeys:[],

                 cascaderProps:{
                 value:'cat_id',
                 label:'cat_name',
                 children:'children'
               },  
                // 被激活页签的名称
                 activeName:'many',
                // 动态参数数据源
                 manyTableData:[],
                // 静态属性数据源
                 onlyTableData:[],
                //  控制添加对话框的显示
                 addDialogVisible:false,
                //  控制编辑对话框显示
                 editDialogVisible:false,
                //  当前选中的参数Id
                 attr_id:'',
                //  添加参数表单
                 addForm:{
                     attr_name:'',
                    
                 },
        
                // 编辑参数表单
                 editForm:{
                     attr_name:'',
                 },
                //  添加表单验证规则
                 addFormRules:{
                    attr_name:[{required: true,message:'请输入参数名称',trigger:'blur'}]
                 },

             }
         },
         created() {
             this.getCateList();
         },
         computed:{
            //  按钮是否被禁用
            isBtnDisable(){
                if(this.selectedKeys.length !== 3)  return true;
                return false;
            },
            //当前选中的三级分类
            cateId(){
                if(this.selectedKeys.length === 3)
                return this.selectedKeys[2];
                return null;
            },
            // 添加对话框的标题文本
            addDialogTitle(){
                if(this.activeName === 'many') return '动态参数';
                return '静态属性'

            }
         },
         methods: {
            //  获取所有的商品分类信息
            async getCateList(){
                const {data:res} = await this.$http.get('categories');
                if(res.meta.status !== 200 ) return this.$message.error('获取分类信息失败')
                this.cateList = res.data;
               
           },
            // 级联选择器选项变化的回调    
           async cateHandleChange(){
                // 如果选中的不是三级分类
                if(this.selectedKeys.length !== 3){
                    this.selectedKeys = [];
                    this.manyTableData = [];
                    this.onlyTableData = [];
                    return;
                   
                }
                 this.getParamsData();
               
              

           },
            //tab页签点击时的回调    
           handleTabClick(){
              console.log(this.activeName);
               this.getParamsData();
           },
           //获取参数的列表数据
           async getParamsData(){
                const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes?sel=${this.activeName}`);
                if(res.meta.status !== 200 ) return;
                console.log(res);
                res.data.forEach(item => {
                    item.attr_vals =   item.attr_vals?item.attr_vals.split(' '):[];
                    item.inputVisible = false;
                    item.inputValue = '';
                });
                console.log(res.data);
                if(this.activeName === 'many'){
                    this.manyTableData = res.data;
                }else{
                    this.onlyTableData = res.data;
                }

           },
           //点击添加按钮的回调
           showAdddialog(){
               this.addDialogVisible = true;
           },
           //监听添加参数对话框的关闭
           addDialogClosed(){
               this.$refs.addFormRef.resetFields();
           },   
           //点击添加参数
           addParams(){
               this.$refs.addFormRef.validate(async valid=>{
                   if(!valid) return;
                   const {data:res}= await this.$http.post(`categories/${this.cateId}/attributes`,{attr_name:this.addForm.attr_name,attr_sel:this.activeName});
                   if(res.meta.status !== 201 ) return this.$message.error('添加失败');
                   this.addDialogVisible = false;
                   this.$message.success('添加成功');
                   this.getParamsData();
               })
              
           },    
           //显示编辑对话框
           showEditDialog(params){
                  this.editDialogVisible = true;
               
                 this.attr_id = params.attr_id;
                 this.editForm.attr_name = params.attr_name;
                 console.log(this.attr_id);

                  
           },
           //实现编辑功能
           editParams(){
                this.$refs.editFormRef.validate(async valid=>{
                    if(!valid) return;
                    const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.attr_id}`,{attr_name:this.editForm.attr_name,attr_sel:this.activeName,});
                    if(res.meta.status !== 200) return this.$message.error('编辑失败');
                    this.$message.success('编辑成功');
                    this.getParamsData();
                    this.editDialogVisible = false;
                })
           },    
           //编辑对话框关闭时的回调
           editDialogClosed(){
              this.$refs.editFormRef.resetFields();
              this.editForm.attr_name='';
           },
           //删除参数
           removeParams(params){
               this.$confirm('此操作将永久删除该'+this.addDialogTitle+', 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async() => {
                const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${params.attr_id}`);
        
                if(res.meta.status !== 200 ) return this.$message.error('删除失败');
                this.getParamsData();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
                });
      
           },  
          // 文本框失去焦点或者按下enter触发的函数   
           async handleInputConfirm(row){
              if(row.inputValue.trim().length === 0){
                 row.inputValue = '';
                 row.inputVisible = false;
                 return;
              }
              row.attr_vals.push(row.inputValue.trim())
              row.inputValue = '';
              row.inputVisible = false;
              if(this.saveAttrVals(row)) this.$message.success('添加成功');
              else
              this.$message.error('添加失败');
        
           },
          //
          async saveAttrVals(row){
              const{data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                  attr_name:row.attr_name,
                  attr_sel:row.attr_sel,
                  attr_vals:row.attr_vals.join(' ')
              })
              if(res.meta.status !== 200 ) return true;
              return false;
          },    
          //显示输入框
          showInput(row){
              row.inputVisible = true;
              //让文本框自动获取焦点   
              //$nextTick方法的作用，当页面上元素被重新渲染后才会指定回调函数中的代码   
               this.$nextTick(_ => {
               this.$refs.saveTagInput.$refs.input.focus();
            });
          },
          //删除参数项的回调
          handleTagClose(row,index){
               row.attr_vals.splice(index,1);
               if(this.saveAttrVals(row)) this.$message.success('删除成功');
               else
               this.$message.error('删除失败');
          }   
            
         },
         
}
</script>

<style lang="less" scoped>
       .cap_opt{
           margin: 15px 0;
       }
       .attr_val_tag{
           margin:0 10px
       }
       .input-new-tag{
           width: 120px;
       }
</style>